package com.hss.common.utils;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class ViewUtil {
	public static void setExpandListViewHeightBasedOnChildren(
			ExpandableListView listView, int groupIndex, int groupHeight) {
		// ListAdapter listAdapter = listView.getAdapter();
		ExpandableListAdapter listAdapter = listView.getExpandableListAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		if (groupIndex != -1){
//			for (int i = 0; i < listAdapter.getGroupCount(); i++) {
//				for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
//					View listItem = listAdapter.getGroupView(i, true, null,
//							listView);
//					// getView(i, null, listView);
//					listItem.measure(0, 0);
//					totalHeight += listItem.getMeasuredHeight();
//				}
//			}
			
//				for (int j = 0; j < listAdapter.getChildrenCount(groupIndex); j++) {
			for (int j = 0; j < listAdapter.getChildrenCount(groupIndex); j++) {
//					View listItem = listAdapter.getGroupView(groupIndex, true, null,
//							listView);
					
				    View childView  = 	listAdapter.getChildView(groupIndex, 0, true, null, listView);
				    childView.measure(0, 0);
				    
				    // getView(i, null, listView);
//					listItem.measure(0, 0);
					totalHeight += childView.getMeasuredHeight();
				}
//				totalHeight += (listView.getDividerHeight() * (listAdapter.getChildrenCount(groupIndex) - 1));
	
		}
		
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + ((listAdapter.getGroupCount()) * groupHeight)  + (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
		listView.setLayoutParams(params);
	}
	
	
	/**
     * 通过动态子组件来设定ListView的高度，使listView可以跟SrollView同时存在
     *
     * @param listView
     */
    public  static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
//        ((MarginLayoutParams) params).setMargins(20, 10, 20, 10);
        listView.setLayoutParams(params);
    }
    
	/**
	 * @author hss
	 * @param v
	 *            控件
	 * @param isShowOrGone
	 *            显示或隐藏
	 */
	public static void  setViewState(View v, boolean isShowOrGone) {
		if (v == null)
			return;
		if (isShowOrGone) {
			if (v.getVisibility() != View.VISIBLE) {
				v.setVisibility(View.VISIBLE);
			}
		} else {
			if (v.getVisibility() != View.GONE) {
				v.setVisibility(View.GONE);
			}
		}
		v = null;
	}
	

	
	/**
	 * 初始化View的高宽
	 * 
	 * @param view
	 */
	@Deprecated
	public static void initViewWH(final View view) {
		view.getViewTreeObserver().addOnGlobalLayoutListener(
				new ViewTreeObserver.OnGlobalLayoutListener() {
					@Override
					public void onGlobalLayout() {
						view.getViewTreeObserver()
								.removeGlobalOnLayoutListener(this);
						System.out.println(view + ", width: " + view.getWidth()
								+ "; height: " + view.getHeight());
					}
				});

	}

	/**
	 * 初始化View的高宽并显示不可见
	 * 
	 * @param view
	 */
	@Deprecated
	public static void initViewWHAndGone(final View view) {
		view.getViewTreeObserver().addOnGlobalLayoutListener(
				new ViewTreeObserver.OnGlobalLayoutListener() {
					@Override
					public void onGlobalLayout() {
						view.getViewTreeObserver()
								.removeGlobalOnLayoutListener(this);
						view.setVisibility(View.GONE);
					}
				});

	}
	
	/**
	 * 获得设备的屏幕宽度
	 * 
	 * @param context
	 * @return
	 */
	public static int getDeviceWidth(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		return manager.getDefaultDisplay().getWidth();
	}

	/**
	 * 获得设备的屏幕高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getDeviceHeight(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		return manager.getDefaultDisplay().getHeight();
	}
	
	
	/**
	 * 获取状态栏高度
	 * 
	 * @param activity
	 * @return
	 */
	@TargetApi(Build.VERSION_CODES.CUPCAKE)
	public static int getStatusBarHeight(Activity activity) {
		Rect frame = new Rect();
		activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		return frame.top;
	}

	/**
	 * 获取状态栏高度＋标题栏高度
	 * 
	 * @param activity
	 * @return
	 */
	public static int getTopBarHeight(Activity activity) {
		return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT)
				.getTop();
	}

	/**
	 * 测量这个view 最后通过getMeasuredWidth()获取宽度和高度.
	 *
	 * @param view
	 *            要测量的view
	 * @return 测量过的view
	 */
	public static void measureView(View view) {
		ViewGroup.LayoutParams p = view.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}

		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight,
					View.MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = View.MeasureSpec.makeMeasureSpec(0,
					View.MeasureSpec.UNSPECIFIED);
		}
		view.measure(childWidthSpec, childHeightSpec);
	}

	/**
	 * 获得这个View的宽度 测量这个view，最后通过getMeasuredWidth()获取宽度.
	 *
	 * @param view
	 *            要测量的view
	 * @return 测量过的view的宽度
	 */
	public static int getViewWidth(View view) {
		measureView(view);
		return view.getMeasuredWidth();
	}

	/**
	 * 获得这个View的高度 测量这个view，最后通过getMeasuredHeight()获取高度.
	 *
	 * @param view
	 *            要测量的view
	 * @return 测量过的view的高度
	 */
	public static int getViewHeight(View view) {
		measureView(view);
		return view.getMeasuredHeight();
	}


	/**
	 * 从父亲布局中移除自己
	 *
	 * @param v
	 */
	public static void removeSelfFromParent(View v) {
		ViewParent parent = v.getParent();
		if (parent != null) {
			if (parent instanceof ViewGroup) {
				((ViewGroup) parent).removeView(v);
			}
		}
	}





	/**
	 * TypedValue官方源码中的算法，任意单位转换为PX单位
	 *
	 * @param unit
	 *            TypedValue.COMPLEX_UNIT_DIP
	 * @param value
	 *            对应单位的值
	 * @param metrics
	 *            密度
	 * @return px值
	 */
	public static float applyDimension(int unit, float value,
									   DisplayMetrics metrics) {
		switch (unit) {
			case TypedValue.COMPLEX_UNIT_PX:
				return value;
			case TypedValue.COMPLEX_UNIT_DIP:
				return value * metrics.density;
			case TypedValue.COMPLEX_UNIT_SP:
				return value * metrics.scaledDensity;
			case TypedValue.COMPLEX_UNIT_PT:
				return value * metrics.xdpi * (1.0f / 72);
			case TypedValue.COMPLEX_UNIT_IN:
				return value * metrics.xdpi;
			case TypedValue.COMPLEX_UNIT_MM:
				return value * metrics.xdpi * (1.0f / 25.4f);
		}
		return 0;
	}

	/**
	 *
	 * @param contentView
	 * @return
	 */
	public static PopupWindow generatePopWindow(View contentView) {
		PopupWindow popupWindow = null;
		popupWindow = new PopupWindow(contentView);
		popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
		popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
//        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.color_text_assist)));

		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);

		return popupWindow;
	}

	private static long lastClickTime;

	/**
	 * 检查按钮是否被恶意快速点击
	 * @return
     */
	public synchronized static boolean isFastClick() {
		long time = System.currentTimeMillis();
		if ( time - lastClickTime < 500) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

}
